﻿using UnityEngine;
using SleepyHippo.Util;
using System;

public class PoolParticleLifeController : MonoBehaviour
{
    public ParticleSystem particle;

    public float delayToRecycle;

    // [System.NonSerialized]
    // public string poolId = null;

    private Action _callback = null;

    public void StartToRecycle(float delay, Action callback = null)
    {
        _callback = callback;
        this.CancelInvoke(nameof(DelayRecycleComplete));
        this.Invoke(nameof(DelayRecycleComplete), delay);
    }

    public void StartToRecycle()
    {
        _callback = null;
        this.CancelInvoke(nameof(DelayRecycleComplete));
        this.Invoke(nameof(DelayRecycleComplete), delayToRecycle);
    }

    private void DelayRecycleComplete()
    {
        Action tmp = _callback;
        Recycle();
        if (tmp != null)
        {
            tmp();
        }
    }

    public void Recycle()
    {
        _callback = null;
        this.CancelInvoke(nameof(DelayRecycleComplete));
        GameObjectPool2.instance.Recycle(this.gameObject, true);
    }

    void OnDestroy()
    {
        _callback = null;
        this.CancelInvoke();
    }

    #region New Logic

    private ParticleSystem[] _particleSystems;

    public void AutoSetRecycleTime()
    {
        if (delayToRecycle > 0)
            return;

        _particleSystems = gameObject.GetComponentsInChildren<ParticleSystem>();

        if (_particleSystems == null)
            return;

        foreach (var particle in _particleSystems)
        {
            if (!(Math.Abs(particle.main.duration - 5f) > 0.01f)
                && !(Math.Abs(particle.main.startLifetime.constant - 5f) > 0.01f))
                continue;

            float t = GetParticleTime(particle);
            if (t > delayToRecycle)
                delayToRecycle = t;
        }
    }

    private float GetParticleTime(ParticleSystem ps)
    {
        ParticleSystem.MainModule main = ps.main;
        float duration = main.startDelay.constant
                         + Mathf.Max(main.duration, main.startLifetime.constant);
        if (main.loop)
        {
            duration *= 2;
        }
        return duration;
    }

    public void SetSpeed(float speed)
    {
        if (_particleSystems == null)
            return;

        foreach (var particle in _particleSystems)
        {
            ParticleSystem.MainModule main = particle.main;
            main.simulationSpeed = speed;
        }
    }

    public void MovePoolParent()
    {
        Transform poolParent = GameObjectPool2.instance.poolParent;
        transform.SetParent(poolParent);
    }

    #endregion
}